package si.wasu.highscores;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class Highscore {

	Context context;

	public Highscore(Context context) {
		this.context = context;
	}

	private void setPreference(String key, int value) {
		SharedPreferences prefs = context.getSharedPreferences("UserTrik", Context.MODE_PRIVATE);
		Editor editor = prefs.edit();
		editor.putInt(key, value);
		editor.commit();
	}

	private int getPreference(String key) {
		SharedPreferences prefs = context.getSharedPreferences("UserTrik", Context.MODE_PRIVATE);
		int score = prefs.getInt(key, 0); // 0 is the default value
		return score;
	}
	
	public void setGlobal(String key, String value) {
		SharedPreferences prefs = context.getSharedPreferences("UserTrik", Context.MODE_PRIVATE);
		Editor editor = prefs.edit();
		editor.putString(key, value);
		editor.commit();
	}
	
	public String getGlobal(String key) {
		SharedPreferences prefs = context.getSharedPreferences("UserTrik", Context.MODE_PRIVATE);
		String score = prefs.getString(key, "0 0 0"); // 0 is the default value
		return score;
	}


	public int getHighscore() {
		return getPreference("globalHighscore");
	}

	public void setHighscore(int highscore) {
		setPreference("globalHighscore", highscore);
	}

	public int getCurrentScore() {
		return getPreference("currentHighscore");
	}

	public void setCurrentScore(int score, int nivo) {
		setPreference("currentHighscore", score);
		String[] all=getGlobal("global").split(" ");
		if(Integer.parseInt(all[nivo-1])<score) {
			String nov="";
			all[nivo-1]=String.valueOf(score);
			
			for (int i = 0; i < all.length; i++) {
				nov+=all[i]+" ";
			}
			setGlobal("global", nov);
			refreshHighscore();
		}
	}
	
	private void refreshHighscore() {
		String[] all=getGlobal("global").split(" ");
		int sum=0;
		for (int i = 0; i < all.length; i++) {
			sum+=Integer.parseInt(all[i]);
		}
		setHighscore(sum);
	}
	
	public int getOpenLevel() {
		return getPreference("openLevel");
	}

	public void setOpenLevel(int openLevel) {
		setPreference("openLevel", openLevel);
	}
}
